declare type Queue = (next: () => void) => Promise<void>;

export default class QueueUtils {
    // 全局队列
    private static instance: QueueUtils;
    public static getInstance() {
        if (!this.instance) {
            this.instance = new QueueUtils();
        }
        return this.instance;
    }

    private queues: Queue[] = [];
    private state: 'complete' | 'execution' = 'complete';
    /**
     * 
     * @param queue 加入队列
     */
    public push(queue: Queue) {
        this.queues.push(queue);
        if (this.state === 'complete') {
            this.run();
        }
    }
    /**
     * 清除队列
     */
    public clear() {
        this.queues = [];
        this.state = 'complete';
    }
    /**
     * 执行队列
     */
    private async run() {
        const queue = this.queues.shift();
        if (!queue) {
            return;
        }
        this.state = 'execution';
        try {
            await queue(() => {
                this.state = 'complete';
                this.run();
            });
        } catch (error) {
            this.state = 'complete';
            this.run();
        }
    }
}



